<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>vs-tree2.0_项目实战</title>
  <link rel="stylesheet" href="../dist/vs-tree.css">
  <link rel="stylesheet" href="./static/css/index.css">
</head>

<body>
  <p>此示例在github中速度受限，请下载代码到本地试验！！！，其中用时为忽略下载时间</p>
  <div>用时：<span id="usetime"></span></div>
  <input id="search" type="text" autocomplete="off" placeholder="输入关键字进行过滤">
  <div id="tree" class="tree-demo"></div>
  <button id="checked" type="button">获取选中元素</button>
  <button id="getNodeById" type="button">根据ID获取节点</button>
  <input id="maxValue" type="number" value="0">
  <button id="setMax" type="button">设置最大可选</button>
  <script src="../dist/vs-tree.js"></script>
  <script>console.time('create:data')</script>
  <script src="./static/js/work.js"></script>
  <script>
    var tree;
    function postMessage(data) {
      console.timeEnd('create:data')
      init()
    }
    function init() {
      console.time('render:tree');
      var time = Date.now()
      tree = new vsTree.default('#tree', {
        data: root[0],
        showCheckbox: true,
        max: 0,
        theme: 'element',
        strictLeaf: true,
        searchFilter: function(keyword, node, data) {
          return node.isLeaf && data.extra && data.extra.keyword && data.extra.keyword.includes(keyword)
        },
        searchRender: function(node, oldDom) {
          const dom = oldDom.querySelector('.vs-tree-text')
          dom.innerHTML = node.data.name + (node.parent ? '<span style="color: #999;">（'+ node.parent.data.name +'）</span>' : '')
          const checkbox = oldDom.querySelector('.vs-checkbox__original')
          if (node.checked) {
            checkbox.disabled = true
          } else {
            oldDom.querySelector('.vs-checkbox__original').addEventListener('change', e => {
              node.setChecked(e.target.checked)
            });
          }
          return oldDom
        },
        checkFilter: function (node) {
          return node.isLeaf
        },
        limitAlert: function () {
          alert('超过最大可选')
        },
        format: function (data, node) {
          // console.log(data, node);
          var child = []
          if (data.obj === 'department') {
            child = depts.filter(v => v.obj === 'department' && v.data.pdid === data.data.did)
            child = child.concat(umap[data.data.did] || [])
            return {
              id: data.data.did,
              name: data.data.name || '---',
              children: child
            }
          }
          const user = infomap[data.uid]
          const parent = node.parent;
          return {
            id: parent && (parent.data.data.did + '_' + data.uid),
            name: user && user.name,
            isLeaf: true,
            children: [],
            extra: {
              dname: parent && parent.data.name,
              did: parent && parent.data.data.did,
              keyword: user && (user.mobile + user.mail + user.pinyin),
            }
          }
        },
        renderContent: function (h, node) {
          if (node.data.obj !== 'department') {
            return false
          }
          const count = getCount(umap, node)
          node.hasChildCount = count
          return h("div", {
            className: "tree-action",
            children: [
              h("span", {
                text: `（${count}）`
              })
            ]
          })
        }
      });
      console.timeEnd('render:tree');
      document.getElementById('usetime').innerHTML = Date.now() - time + 'ms'
    }

    function getCount(umap, node) {
      if (!umap[node.data.data.did]) return 0
      let count = 0
      const calc = (node) => {
        if (node.data.obj !== 'department') return
        count += (umap[node.data.data.did] && umap[node.data.data.did].length) || 0
        if (node.childNodes) {
          for (let i = 0, len = node.childNodes.length; i < len; i++) {
            const v = node.childNodes[i];
            calc(v)
          }
        }
      }
      calc(node)
      return count
    }

    document.getElementById("checked").onclick = function () {
      console.log(tree);
      console.log(tree.getCheckedNodes());
    }

    document.getElementById('search').addEventListener('input', (e) => {
      // tree.filter(e.target.value, true)
      tree.filter(e.target.value, true)
    })

    document.getElementById('setMax').addEventListener('click', (e) => {
      tree.setMaxValue(document.getElementById('maxValue').value || 0)
    })

    document.getElementById('getNodeById').addEventListener('click', (e) => {
      const id = "287573_100003049742"
      tree.getNodeById(id) && tree.getNodeById(id).setChecked(true);
    })
  </script>
</body>

</html>